package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
public class OrderSettingServiceImpl implements OrderSettingService {


    @Autowired
    OrderSettingDao orderSettingDao;

    @Override
    @Transactional
    public void addOrderSettingList(List<OrderSetting> orderSettingList) {
        if (orderSettingList!= null && orderSettingList.size() > 0){
            for (OrderSetting orderSetting : orderSettingList) {
                add(orderSetting);
            }
        }
    }

    /**
     * 业务分析
     *  添加时要先判断是否已经进行预约设置，
     *      如果已经设置，则修改
     *          在修改时要判断， 已预约人数是否小于可预约
     *           如果大于可预约，则不能修改
     *           如果小于可预约，则能修改
     *      如果没有设置，则添加
     * @param orderSetting
     */
    @Override
    @Transactional
    public void add(OrderSetting orderSetting){
//根据预约设置的日期查询数据库中的预约设置对象
        OrderSetting orderSettingDb = orderSettingDao.findByDate(orderSetting.getOrderDate());
        if(orderSettingDb == null){
            //没有进行预约设置，直接添加
            orderSettingDao.add(orderSetting);
        }else{
            //已经进行预约设置，修改
            //获取已预约人数
            int reservations = orderSettingDb.getReservations();
            //获取可预约人数
            int number = orderSetting.getNumber();
            //已预约人数大于可预约人数，抛出异常
            if(reservations > number){
                throw  new RuntimeException("已预约人数大于可预约人数，批量导入失败!!!!");
            }
            //已预约人数小于等于可预约人数，直接修改
            else{
                orderSettingDao.edit(orderSetting);
            }
        }
    }

    @Override
    public List<OrderSetting> getOrderSettingByMonth(String date) {
        String startDate = DateUtils.getFirstDayByMonth(date);
        String endDate = DateUtils.getLastDayByMonth(startDate);
        List<OrderSetting> orderSettingList = orderSettingDao.findOrderSettingsByDate(startDate, endDate);
        return orderSettingList;
    }

    /**
     * @Author erlong
     * @param today
     */
    @Override
    @Transactional
    public void clearOrdersettingData(String today) {

        orderSettingDao.clearOrdersettingData(today);

    }
}
